package transfers

import (
	"io"
	"crypto/sha256"
	"fmt"
	"github.com/djimenez/iconv-go"
	"github.com/dutchcoders/goftp"
)

type FtpTransfer struct {
	Resource
}

func (p *FtpTransfer) TotalSize() (size int, err error) {
	return
}

func (p *FtpTransfer) PartDownload(startPos int, size int, c chan []byte) {
	var err error
	var ftp *goftp.FTP

	// For debug messages: goftp.ConnectDbg("ftp.server.com:21")
	addr := "piaohua668.com:31225"
	if ftp, err = goftp.Connect(addr); err != nil {
		panic(err)
	}

	defer ftp.Close()
	fmt.Println("Successfully connected to", addr)

	// Username / password authentication
	if err = ftp.Login("p", "p"); err != nil {
		panic(err)
	}

	if err = ftp.Cwd("/"); err != nil {
		panic(err)
	}

	var files []string
	if files, err = ftp.List(""); err != nil {
		panic(err)
	}

	var out string
	for _, file := range files {
		if out, err = iconv.ConvertString(file, "gb2312", "utf-8"); err != nil {
			continue
		}

		println(out)
	}

	//fmt.Println("Directory listing:", files)

	path := "ThunderSpeed1.0.25.256.zip"
	out, err = ftp.Retr(path, func(r io.Reader) error {
		var hasher = sha256.New()
		if _, err := io.Copy(hasher, r); err != nil {
			return err
		}

		if err != nil {
			return err
		}

		hash := fmt.Sprintf("%s %x", path, sha256.Sum256(nil))
		fmt.Println(hash)

		return err
	})

	return
}

func NewFtpTransfer(resource Resource) *FtpTransfer {
	return &FtpTransfer{resource}
}